<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->

<template>
  <div class="app-container">

    <div class="main-content">
      <!-- 左侧科室列表 -->
      <!-- 在线问诊
       <ChatComponent /> -->
      <aside class="department-list">
        <el-input v-model="searchKeyword" placeholder="搜索科室" prefix-icon="Search" clearable class="search-input" />

        <el-tree :data="departments" :props="defaultProps" @node-click="handleDepartmentSelect"
          class="department-tree" />
      </aside>

      <!-- 右侧医生列表 -->
      <main class="doctor-list">
        <h2 class="section-title">{{ currentDepartment }}</h2>
        <div class="doctor-grid">
          <el-card v-for="doctor in doctors" :key="doctor.id" class="doctor-card">
            <div class="doctor-info">
              <img :src="doctor.avatar" :alt="doctor.name" class="doctor-avatar" />
              <h3>{{ doctor.name }}</h3>
              <p class="doctor-title">{{ doctor.title }}</p>
              <p class="doctor-specialty">{{ doctor.specialty }}</p>
              <div class="schedule-info">
                <!-- <p>可预约时间：{{ doctor.availableTime }}</p> -->
                <!-- <p>挂号费：<span class="fee">¥{{ doctor.fee }}</span></p> -->
              </div>
              <el-button type="primary" @click="handleAppointment(doctor)">
                预约挂号
              </el-button>
            </div>
          </el-card>
        </div>

        <div class="talkabout" @click="openTalck"></div>
      </main>
    </div>
    <!-- 预约弹窗 -->
    <el-dialog v-model="dialogVisible" title="预约挂号" width="700px" class="appointment-dialog">
      <div v-if="selectedDoctor" class="doctor-info">
        <div class="doctor-header">
          <img :src="selectedDoctor.avatar" class="doctor-avatar" />
          <div class="doctor-details">
            <h3>{{ selectedDoctor.name }}</h3>
            <p class="doctor-meta">{{ selectedDoctor.title }} | {{ selectedDoctor.specialty }}</p>
          </div>
        </div>
      </div>

      <el-tabs v-model="activeTab" type="card" class="schedule-tabs" v-loading="isconfirmAppointment">
        <el-tab-pane v-for="date in groupedSchedules" :key="date.date" :label="formatDateLabel(date.date)">
          <div class="schedule-grid">
            <div v-for="schedule in date.schedules" :key="schedule.scheduleId" class="schedule-card" :class="{
              'available': schedule.deleteNumber > 0,
              'full': schedule.deleteNumber <= 0
            }">
              <div class="schedule-header">
                <span class="time-slot">{{ schedule.timeSlot }}</span>
                <el-tag :type="schedule.maxAppointments > 0 ? 'success' : 'info'" size="small">
                  {{ schedule.maxAppointments > 0 ? `剩余 ${schedule.maxAppointments}个` : '已约满' }}
                </el-tag>
              </div>
              <div class="schedule-fee">
                挂号费: <span class="fee">¥{{ schedule.registrationFee }}</span>
              </div>
              <el-button type="primary" size="small" :disabled="schedule.deleteNumber <= 0"
                @click="selectSchedule(schedule)" class="select-btn">
                选择该时段
              </el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- 选择就诊人 -->
      <div class="patient-selector" v-if="selectedSchedule">
        <el-form :model="appointmentForm" label-width="80px">
          <el-form-item label="就诊人">
            <el-select v-model="appointmentForm.patientId" placeholder="请选择就诊人">
              <el-option v-for="patient in patients" :key="patient.id" :label="patient.name" :value="patient.id" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :disabled="!selectedSchedule || !appointmentForm.patientId"
            @click="confirmAppointment">
            确认预约 (¥{{ selectedSchedule?.registrationFee || 0 }})
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增：预约成功后的天气弹窗 -->
    <!-- 删除重复的弹窗，保留这个 -->
    <el-dialog v-model="weatherDialogVisible" title="正在跳转到支付页面" width="500px" class="weather-dialog">
      <div class="weather-content">
        <h3>✅ 预约成功 等待页面跳转</h3>

        <div class="appointment-summary">
          <p>医生：{{ selectedDoctor?.name }}</p>
          <p>时间：{{ selectedSchedule?.date }} {{ selectedSchedule?.timeSlot }}</p>
        </div>

        <div v-if="weatherData" class="weather-info">
          <h4>当日天气提醒</h4>
          <div class="weather-display">
            <img :src="getWeatherIcon(weatherData.weather)" class="weather-icon" />
            <div class="weather-details">
              <p>{{ weatherData.weather }} ({{ weatherData.tempMin }}°C ~ {{ weatherData.tempMax }}°C)</p>
              <p>湿度 {{ weatherData.humidity }}% • 风速 {{ weatherData.wind }}级</p>
              <p class="weather-tip">{{ getWeatherTip(weatherData.weather) }}</p>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button type="primary" @click="weatherDialogVisible = false">确定</el-button>
      </template>
    </el-dialog>

    <!-- 在template部分添加支付确认弹窗  paymentDialogVisible-->
    <el-dialog v-model="paymentDialogVisible" title="支付确认" width="400px">
      <div class="payment-confirm">
        <p>您已成功预约，是否立即支付挂号费？</p>
        <p class="payment-amount">支付金额: ¥{{ selectedSchedule?.registrationFee || 0 }}</p>
      </div>

      <template #footer>
        <el-button @click="handlePaymentCancel">稍后支付</el-button>
        <el-button type="primary" @click="handlePaymentConfirm">立即支付</el-button>
      </template>
    </el-dialog>

    <ChatComponent v-if="chatshow" class="chatshow"></ChatComponent>

  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import ChatComponent from "../ChatComponent/index1.vue"
import { getAllDepartement, getDoctorsByDepartID, getScheduless, insertOrder, getWeather, alipayOrder, buildAppointment } from "@/api/healthcare"
const activeMenu = ref('1');
const searchKeyword = ref('');
const currentDepartment = ref('内科 - 心血管内科');
const dialogVisible = ref(false);
const selectedDoctor = ref(null);
const isconfirmAppointment = ref(false);
const departments = ref([
  {
    label: '内科',
  },
  {
    label: '外科',
    id: '2',
  }
]); const weatherDialogVisible = ref(false);
const weatherData = ref(null);
const paymentDialogVisible = ref(false);
const orderInfo = ref(null); // 存储订单信息
let chatshow = ref(false)
const doctors = ref();

let user = {};
const patients = ref([
]);
// 在script部分添加以下代码
const activeTab = ref('')
const selectedSchedule = ref(null)
const schedulesData = ref([])
// 格式化日期标签 
const formatDateLabel = (dateStr) => {
  const date = new Date(dateStr)
  const today = new Date()
  const tomorrow = new Date(today)
  tomorrow.setDate(tomorrow.getDate() + 1)

  if (date.toDateString() === today.toDateString()) {
    return '今天'
  } else if (date.toDateString() === tomorrow.toDateString()) {
    return '明天'
  } else {
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const month = date.getMonth() + 1
    const day = date.getDate()
    const weekday = weekdays[date.getDay()]
    return `${month}月${day}日 ${weekday}`
  }
}

// 按日期分组排班数据
const groupedSchedules = computed(() => {
  let groups = {}
  schedulesData.value.forEach(schedule => {
    if (!groups[schedule.date]) {
      groups[schedule.date] = {
        date: schedule.date,
        schedules: []
      }
    }
    groups[schedule.date].schedules.push(schedule)
  })

  // 按日期排序
  return Object.values(groups).sort((a, b) => {
    return new Date(a.date) - new Date(b.date)
  })
})

// 选择排班时段
const selectSchedule = (schedule) => {
  selectedSchedule.value = schedule
}
function openTalck() {
  chatshow.value = !chatshow.value;
}
// 修改获取排班数据的函数
const getSchedules = (doctorId: any) => {
  getScheduless({ doctorId: doctorId }, { custom: { showLoading: true } })
    .then(res => {
      if (res.code === 200) {
        schedulesData.value = res.data
        // 默认选择第一个标签页
        if (res.data.length > 0) {
          activeTab.value = res.data[0].date
        }
      }
    })
    .catch(error => {
      console.error("获取排班失败", error)
      ElMessage.error('获取排班信息失败')
    })
}

const confirmAppointment = async () => {
  if (!selectedSchedule.value || !appointmentForm.value.patientId) {
    ElMessage.warning('请选择就诊时段和就诊人');
    return;
  }


  const params = {
    scheduleId: selectedSchedule.value.scheduleId,
    patientId: appointmentForm.value.patientId,
    doctorId: selectedDoctor.value.doctorId,
    appointmentDate: selectedSchedule.value.date,
    paymentAmount: selectedSchedule.value.registrationFee,
    timeSolt: selectedSchedule.value.timeSlot,
    totalAmount: selectedSchedule.value.registrationFee,
    payType: 1,
    paymentType: 1,
    status: 1,
    patientName: selectedDoctor.value.name,
    idCard: user.idCard,
    date: selectedSchedule.value.date,
    userId: user.userId,
  };

  try {
    isconfirmAppointment.value = true;
    const res = await buildAppointment(params, { custom: { showLoading: true } });
    if (res.code === 200) {
      isconfirmAppointment.value = false;
      dialogVisible.value = false;
      if (res.data instanceof Object) {
        orderInfo.value = res.data;
        paymentDialogVisible.value = true; // 显示支付确认弹窗
      } else {
        ElMessage.warning("不可以预约同一天同一个时间段的医生哦");
      }
    } else {
      ElMessage.error(res.message || '预约失败，请稍后重试');
    }
  } catch (error) {
    ElMessage.error(`预约失败：${error.message || '网络错误，请检查网络连接'}`);
  }
};

// 处理支付确认
const handlePaymentConfirm = async () => {
  try {
    const paramsOrder = {
      TradeNo: orderInfo.value.orderNumber,
      totalAmount: orderInfo.value.totalAmount,
      subject: "预约订单",
      scheduleId: selectedSchedule.value.scheduleId,
      patientId: appointmentForm.value.patientId,
      doctorId: selectedDoctor.value.doctorId,
      appointmentDate: selectedSchedule.value.date,
      paymentAmount: selectedSchedule.value.registrationFee,
      timeSolt: selectedSchedule.value.timeSlot,
      userId: user.userId,
      payType: 1,
      paymentType: 1,
      status: 1,
      patientName: selectedDoctor.value.name,
      idCard: user.idCard,
      date: selectedSchedule.value.date
    };
    debugger
    const alipayRes = await alipayOrder(paramsOrder, { custom: { showLoading: true } });
    // 创建一个隐藏的div来存放支付宝返回的form
    const div = document.createElement('div');
    div.innerHTML = alipayRes.data;
    document.body.appendChild(div);

    // 自动提交表单
    const form = div.querySelector('form');
    if (form) {
      form.submit();
    } else {
      ElMessage.error('支付表单生成失败');
    }

    paymentDialogVisible.value = false;
    weatherDialogVisible.value = true; // 显示预约成功和天气信息
  } catch (error) {
    ElMessage.error('支付请求失败: ' + error.message);
  }
};

// 处理取消支付
const handlePaymentCancel = () => {
  paymentDialogVisible.value = false;
  // weatherDialogVisible.value = true; // 显示预约成功和天气信息
  ElMessage.success('预约成功，请记得在就半小时内完成支付');
};
// 新增天气相关函数
const fetchWeatherData = async (date) => {
  // 这里应该是调用天气API的代码
  // 为了演示，我们返回模拟数据
  return new Promise(resolve => {
    setTimeout(() => {
      const weatherTypes = ['晴', '多云', '阴', '小雨', '中雨', '大雨', '雷阵雨'];
      const randomWeather = weatherTypes[Math.floor(Math.random() * weatherTypes.length)];

      resolve({
        date: date,
        weather: randomWeather,
        temperature: Math.floor(Math.random() * 15) + 10, // 10-25°C
        humidity: Math.floor(Math.random() * 40) + 50, // 50-90%
        wind: Math.floor(Math.random() * 4) + 1, // 1-5级
      });
    }, 500);
  });
};

const getWeatherIcon = (weather) => {
  // 根据天气返回对应的图标URL
  const icons = {
    '晴': '/weather-icons/sunny.png',
    '多云': '/weather-icons/cloudy.png',
    '阴': '/weather-icons/overcast.png',
    '小雨': '/weather-icons/light-rain.png',
    '中雨': '/weather-icons/moderate-rain.png',
    '大雨': '/weather-icons/heavy-rain.png',
    '雷阵雨': '/weather-icons/thunderstorm.png',
  };
  return icons[weather] || '/weather-icons/unknown.png';
};

const getWeatherTip = (weather) => {
  const tips = {
    '晴': '天气晴朗，建议佩戴太阳镜和防晒霜',
    '多云': '多云天气，适宜出行',
    '阴': '阴天，可能会下雨，建议带伞',
    '小雨': '有小雨，请带好雨具',
    '中雨': '有中雨，请注意出行安全',
    '大雨': '有大雨，建议改期或注意安全',
    '雷阵雨': '有雷阵雨，请尽量避免外出',
  };
  return tips[weather] || '请关注当天天气变化';
};
const appointmentForm = ref({
  appointmentDate: '',
  patientId: '',
});

const defaultProps = {
  children: 'children',
  label: 'name'
};

const handleDepartmentSelect = (data: any) => {
  if (!data.children) {
    currentDepartment.value = `${data.description}`;
    getDoctors(data.departmentId);
    // 根据 科室信息 查询对应的医生的排班信息
  }
};

const handleAppointment = (doctor: any) => {
  selectedDoctor.value = doctor;
  dialogVisible.value = true;
  getSchedules(doctor.doctorId);
};

// medical/getSchedules
function getDoctors(departmentId: any) {
  getDoctorsByDepartID({ departmentId: departmentId }, { custom: { showLoading: true } }).then(res => {
    console.log("res.data", res.data);
    doctors.value = res.data;
  }).catch(error => {
    console.error("res.data");
  })
}
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7;
};


function getAllDepartment() {
  getAllDepartement(null, { custom: { showLoading: true } })
    .then(response => {
      departments.value = response.data;
      console.log('.................................', response.data);
    })
    .catch(error => {
      console.error('查询失败', error);
    });
}
onMounted(() => {
  getAllDepartment();
  getDoctors(1);
  user = JSON.parse(localStorage.getItem("user"));
  patients.value.push({ name: user.name, id: user.userId });

})
</script>

<style scoped>
.app-container {
  min-height: 100vh;
  /* background-color: #f5f7fa; */
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 80px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 40px;
  z-index: 1000;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.logo {
  width: 50px;
  height: 50px;
}

.logo-section h1 {
  font-size: 24px;
  color: #2c3e50;
  margin: 0;
}

.nav-menu {
  font-size: 16px;
}

.main-content {
  display: flex;
  /* padding-top: 80px; */
  min-height: calc(100vh - 80px);
}

.department-list {
  width: 300px;
  background-color: #fff;
  padding: 20px;
  border-right: 1px solid #e6e6e6;
}

.search-input {
  margin-bottom: 20px;
}

.department-tree {
  font-size: 16px;
}

.doctor-list {
  flex: 1;
  padding: 30px;
}

.section-title {
  font-size: 24px;
  color: #2c3e50;
  margin-bottom: 30px;
}

.doctor-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 30px;
}

.doctor-card {
  transition: transform 0.3s;
}

.doctor-card:hover {
  transform: translateY(-5px);
}

.doctor-info {
  text-align: center;
}

.doctor-avatar {
  width: 233px;
  height: 150px;
  border-radius: 50%;
  margin-bottom: 15px;
}

.doctor-info h3 {
  font-size: 20px;
  color: #2c3e50;
  margin: 0 0 10px;
}

.doctor-title {
  font-size: 16px;
  color: #409EFF;
  margin: 5px 0;
}

.doctor-specialty {
  font-size: 14px;
  color: #606266;
  margin: 10px 0;
  line-height: 1.5;
}

.schedule-info {
  margin: 15px 0;
  font-size: 14px;
  color: #606266;
}

.fee {
  color: #f56c6c;
  font-weight: bold;
}

.appointment-dialog {
  font-size: 16px;
}

.appointment-form {
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.chatshow {
  position: fixed;
  top:-10%;
  right: 21%;
  border-radius: 1px solid red !important;
}

:deep(.el-button) {
  font-size: 16px;
  padding: 12px 20px;
}

:deep(.el-input__inner) {
  font-size: 16px;
  height: 40px;
}

:deep(.el-tree-node__content) {
  height: 40px;
}

:deep(.el-menu-item) {
  font-size: 16px;
}

/* 医生信息样式 */
.doctor-info {
  margin-bottom: 20px;
}

.doctor-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.doctor-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-right: 15px;
  object-fit: cover;
}

.doctor-details h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.doctor-meta {
  margin: 5px 0 0;
  font-size: 14px;
  color: #666;
}

/* 排班标签页样式 */
.schedule-tabs {
  margin-top: 15px;
}

.schedule-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  margin-top: 10px;
}

/* 排班卡片样式 */
.schedule-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  transition: all 0.3s;
}

.schedule-card.available {
  background-color: #f6ffed;
  border-color: #b7eb8f;
}

.schedule-card.full {
  background-color: #fafafa;
  border-color: #d9d9d9;
  opacity: 0.8;
}

.schedule-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.schedule-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.time-slot {
  font-weight: 500;
  color: #333;
}

.schedule-fee {
  font-size: 13px;
  color: #666;
  margin-bottom: 10px;
}

.fee {
  color: #f56c6c;
  font-weight: bold;
}

.select-btn {
  width: 100%;
}

/* 就诊人选择样式 */
.patient-selector {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

/* 对话框底部样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .schedule-grid {
    grid-template-columns: 1fr;
  }

  .appointment-dialog {
    width: 90% !important;
  }
}

/* 新增天气弹窗样式 */
.weather-dialog {
  text-align: center;
}

.weather-dialog .el-dialog__body {
  padding: 20px;
}

.weather-content {
  text-align: center;
}

.weather-content h3 {
  color: #67C23A;
  font-size: 20px;
  margin-bottom: 20px;
}

.weather-info {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.talkabout {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  position: fixed;
  bottom: 7%;
  right: 2%;
  background-color: red;
  background-image: url("https://org-tt-bucket.oss-cn-chengdu.aliyuncs.com/img/aec9bbf349acedb3a0b3ec54f3f28441.png");
  background-repeat: no-repeat;
  background-size: cover;
  cursor: pointer;
}

.weather-icon img {
  width: 80px;
  height: 80px;
  margin-right: 20px;
}

.weather-details {
  text-align: left;
}

.weather-details p {
  margin: 5px 0;
  font-size: 15px;
}

.weather-tip {
  color: #E6A23C;
  font-weight: bold;
  margin-top: 10px !important;
}

.appointment-summary {
  margin-top: 20px;
  padding: 15px;
  background-color: #ecf5ff;
  border-radius: 8px;
  text-align: left;
}

.appointment-summary p {
  margin: 8px 0;
  font-size: 15px;
}
</style>
